package com.feng.common.utils;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.text.CharPool;
import cn.hutool.core.util.IdUtil;
import com.feng.common.vo.ApiRest;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author：ChenFeng
 * @describe：
 */
public class UploadUtil {
    public static final String ACCESS_KEY = "nzxMGum77lYLD19_8_RKuKx2w0KpTVSWXXubu4tA";
    public static final String SECRET_KEY = "oTp56iyrft_Vw8NYWv_9fHUWzhK_TQZlqqe_ckz1";
    public static final String DOMAIN = "http://rs4oipopi.bkt.clouddn.com/";
    public static String bucket = "dik";

    public static ApiRest<String> uploadFile(MultipartFile file) {
        if (file == null) {
            throw new NullPointerException("文件不能为空");
        }
        String suffix = FileNameUtil.getSuffix(file.getOriginalFilename());
        String path = IdUtil.fastSimpleUUID() + CharPool.DOT + suffix;

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.regionCnEast2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        try {
            Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(file.getBytes(), path, upToken);
            return ApiRest.success("文件上传成功", DOMAIN + path);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiRest.failure("文件上传失败",null);
        }
    }

}
